package com.example.scanningshardutils.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.scanningshardutils.R;
import com.example.scanningshardutils.utils.FileUtilsJ;
import com.example.scanningshardutils.utils.QrCodeUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ShardActivity extends AppCompatActivity {
    public static Drawable logo = null;

    public static void getInstance(FragmentActivity activity, Drawable logo, String url) {
        Intent intent = new Intent(activity, ShardActivity.class);
        ShardActivity.logo = logo;
        intent.putExtra("URL", url);
        activity.startActivity(intent);
    }

    TextView img;
    Bitmap bitmap1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_utils_shard);
        img = findViewById(R.id.shard);
        checkAndRequestPermission(1);
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.but_shard).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAndRequestPermission(0);
            }
        });
    }


    /**
     * ----------非常重要----------
     * <p>
     * Android6.0以上的权限适配简单示例：
     * <p>
     * 如果targetSDKVersion >= 23，那么必须要申请到所需要的权限，再调用广点通SDK，否则广点通SDK不会工作。
     * <p>
     * Demo代码里是一个基本的权限申请示例，请开发者根据自己的场景合理地编写这部分代码来实现权限申请。
     * 注意：下面的`checkSelfPermission`和`requestPermissions`方法都是在Android6.0的SDK中增加的API，如果您的App还没有适配到Android6.0以上，则不需要调用这些方法，直接调用广点通SDK即可。
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission(int type) {
        this.type = type;
        List<String> lackedPermission = new ArrayList<String>();

        if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        // 权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            if (type == 1) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final Bitmap url = QrCodeUtil.createQRCode(getIntent().getStringExtra("URL"), FileUtilsJ.gitBitmap(logo));
                        Bitmap bitmap = FileUtilsJ.convertViewToBitmap(img);
                        bitmap1 = FileUtilsJ.combineBitmap(bitmap, url);
                    }
                }).start();
            } else {
                if (null == bitmap1){
                    checkAndRequestPermission(1);
                }else{
                    File shard = FileUtilsJ.saveImageToGallery(bitmap1, "shard");
                    String imageUri = FileUtilsJ.insertImageToSystem(ShardActivity.this, shard.getPath());
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_TEXT, "一些文字");
                    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageUri));
                    shareIntent.setType("image/*");
                    startActivity(shareIntent);//这样分享就不带标题了
                }
            }

        } else {
            // 请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限，如果获得权限就可以调用SDK，否则不要调用SDK。
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }

    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    int type = 0;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1024 && hasAllPermissionsGranted(grantResults)) {
            if (type == 1) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final Bitmap url = QrCodeUtil.createQRCode(getIntent().getStringExtra("URL"), FileUtilsJ.gitBitmap(logo));
                        Bitmap bitmap = FileUtilsJ.convertViewToBitmap(img);
                        bitmap1 = FileUtilsJ.combineBitmap(bitmap, url);
                    }
                }).start();
            } else {
                if (null == bitmap1) return;
                File shard = FileUtilsJ.saveImageToGallery(bitmap1, "shard");
                String imageUri = FileUtilsJ.insertImageToSystem(ShardActivity.this, shard.getPath());
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_TEXT, "一些文字");
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageUri));
                shareIntent.setType("image/*");
                startActivity(shareIntent);//这样分享就不带标题了
            }
        } else {
            // 如果用户没有授权，那么应该说明意图，引导用户去设置里面授权。
            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            finish();
        }
    }
}
